<template>
  <div class="integration-dashboard">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="dashboard-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>系统集成总数</span>
              <el-tag type="info">{{ statistics.totalSystems }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="status-list">
              <div class="status-item">
                <span class="label">正常</span>
                <span class="value success">{{ statistics.normalSystems }}</span>
              </div>
              <div class="status-item">
                <span class="label">异常</span>
                <span class="value danger">{{ statistics.errorSystems }}</span>
              </div>
              <div class="status-item">
                <span class="label">测试中</span>
                <span class="value warning">{{ statistics.testingSystems }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>消息队列状态</span>
              <el-tag type="info">{{ statistics.totalQueues }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="queue-metrics">
              <div class="metric-item">
                <span class="label">活跃队列</span>
                <span class="value">{{ statistics.activeQueues }}</span>
              </div>
              <div class="metric-item">
                <span class="label">消息积压</span>
                <span class="value warning">{{ statistics.backlogMessages }}</span>
              </div>
              <div class="metric-item">
                <span class="label">消费延迟</span>
                <span class="value">{{ statistics.avgConsumeDelay }}ms</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>监控告警</span>
              <el-tag type="info">{{ statistics.totalMonitors }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="alert-metrics">
              <div class="metric-item">
                <span class="label">今日告警</span>
                <span class="value danger">{{ statistics.todayAlerts }}</span>
              </div>
              <div class="metric-item">
                <span class="label">未处理</span>
                <span class="value warning">{{ statistics.pendingAlerts }}</span>
              </div>
              <div class="metric-item">
                <span class="label">平均响应</span>
                <span class="value">{{ statistics.avgResponseTime }}分钟</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>系统健康度</span>
              <el-tag :type="getHealthTagType(statistics.healthScore)">
                {{ statistics.healthScore }}%
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="health-metrics">
              <el-progress
                :percentage="statistics.healthScore"
                :status="getHealthStatus(statistics.healthScore)"
                :stroke-width="15"
              />
              <div class="metric-item">
                <span class="label">系统可用性</span>
                <span class="value">{{ statistics.systemAvailability }}%</span>
              </div>
              <div class="metric-item">
                <span class="label">平均响应时间</span>
                <span class="value">{{ statistics.avgSystemResponseTime }}ms</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统状态图表 -->
    <el-row :gutter="20" class="dashboard-charts">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>系统调用趋势</span>
              <el-radio-group v-model="systemTrendTimeRange" size="small">
                <el-radio-button label="day">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="systemTrendChartRef"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>消息队列监控</span>
              <el-radio-group v-model="queueMonitorTimeRange" size="small">
                <el-radio-button label="hour">1小时</el-radio-button>
                <el-radio-button label="day">24小时</el-radio-button>
                <el-radio-button label="week">7天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="queueMonitorChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 告警列表 -->
    <el-card shadow="hover" class="alert-list-card">
      <template #header>
        <div class="card-header">
          <span>最近告警</span>
          <div class="header-operations">
            <el-button type="primary" link @click="handleRefreshAlerts">
              刷新
            </el-button>
            <el-button type="primary" link @click="handleExportAlerts">
              导出
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="alertList" border v-loading="alertLoading">
        <el-table-column prop="time" label="告警时间" width="180" />
        <el-table-column prop="type" label="告警类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAlertTypeTag(row.type)">
              {{ getAlertTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="告警来源" width="150" />
        <el-table-column prop="level" label="告警级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlertLevelTag(row.level)">
              {{ getAlertLevelLabel(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="告警内容" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlertStatusTag(row.status)">
              {{ getAlertStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewAlertDetail(row)">
              详情
            </el-button>
            <el-button type="primary" link @click="handleProcessAlert(row)">
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="alertPage"
          v-model:page-size="alertPageSize"
          :total="alertTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleAlertPageSizeChange"
          @current-change="handleAlertPageChange"
        />
      </div>
    </el-card>

    <!-- 告警详情对话框 -->
    <el-dialog
      v-model="alertDetailVisible"
      title="告警详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="告警时间">
          {{ currentAlert.time }}
        </el-descriptions-item>
        <el-descriptions-item label="告警类型">
          <el-tag :type="getAlertTypeTag(currentAlert.type)">
            {{ getAlertTypeLabel(currentAlert.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="告警来源">
          {{ currentAlert.source }}
        </el-descriptions-item>
        <el-descriptions-item label="告警级别">
          <el-tag :type="getAlertLevelTag(currentAlert.level)">
            {{ getAlertLevelLabel(currentAlert.level) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="告警内容" :span="2">
          {{ currentAlert.content }}
        </el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getAlertStatusTag(currentAlert.status)">
            {{ getAlertStatusLabel(currentAlert.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理时间">
          {{ currentAlert.processTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="处理人" :span="2">
          {{ currentAlert.processor || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="处理备注" :span="2">
          {{ currentAlert.processRemark || '-' }}
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <el-button @click="alertDetailVisible = false">关闭</el-button>
        <el-button
          v-if="currentAlert.status === 'pending'"
          type="primary"
          @click="handleProcessAlert(currentAlert)"
        >
          处理告警
        </el-button>
      </template>
    </el-dialog>

    <!-- 处理告警对话框 -->
    <el-dialog
      v-model="processAlertVisible"
      title="处理告警"
      width="500px"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理方式" prop="processType">
          <el-select v-model="processForm.processType" placeholder="请选择处理方式">
            <el-option label="已解决" value="resolved" />
            <el-option label="忽略" value="ignored" />
            <el-option label="转交" value="transferred" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processAlertVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcessAlert" :loading="processing">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  getSystemList,
  getQueueList,
  getMonitorList,
  getMonitorHistory,
  processAlert,
  exportAlerts
} from '@/api/message'

// 统计数据
const statistics = reactive({
  totalSystems: 0,
  normalSystems: 0,
  errorSystems: 0,
  testingSystems: 0,
  totalQueues: 0,
  activeQueues: 0,
  backlogMessages: 0,
  avgConsumeDelay: 0,
  totalMonitors: 0,
  todayAlerts: 0,
  pendingAlerts: 0,
  avgResponseTime: 0,
  healthScore: 0,
  systemAvailability: 0,
  avgSystemResponseTime: 0
})

// 图表相关
const systemTrendChartRef = ref(null)
const queueMonitorChartRef = ref(null)
let systemTrendChart = null
let queueMonitorChart = null
const systemTrendTimeRange = ref('day')
const queueMonitorTimeRange = ref('hour')

// 告警列表相关
const alertList = ref([])
const alertLoading = ref(false)
const alertPage = ref(1)
const alertPageSize = ref(10)
const alertTotal = ref(0)

// 告警详情相关
const alertDetailVisible = ref(false)
const currentAlert = ref({})
const processAlertVisible = ref(false)
const processFormRef = ref(null)
const processForm = reactive({
  processType: '',
  remark: ''
})
const processing = ref(false)

// 表单验证规则
const processRules = {
  processType: [
    { required: true, message: '请选择处理方式', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入处理备注', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  initCharts()
  loadDashboardData()
  loadAlertList()
  
  // 定时刷新数据
  const timer = setInterval(() => {
    loadDashboardData()
  }, 60000) // 每分钟刷新一次
  
  onUnmounted(() => {
    clearInterval(timer)
    systemTrendChart?.dispose()
    queueMonitorChart?.dispose()
  })
})

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // 系统调用趋势图表
  systemTrendChart = echarts.init(systemTrendChartRef.value)
  systemTrendChart.setOption({
    title: {
      text: '系统调用趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['调用次数', '成功率', '平均响应时间']
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '调用次数',
        position: 'left'
      },
      {
        type: 'value',
        name: '成功率/响应时间',
        position: 'right',
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '调用次数',
        type: 'bar',
        data: []
      },
      {
        name: '成功率',
        type: 'line',
        yAxisIndex: 1,
        data: []
      },
      {
        name: '平均响应时间',
        type: 'line',
        yAxisIndex: 1,
        data: []
      }
    ]
  })
  
  // 消息队列监控图表
  queueMonitorChart = echarts.init(queueMonitorChartRef.value)
  queueMonitorChart.setOption({
    title: {
      text: '消息队列监控'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['消息数量', '消费速率', '积压数量']
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '消息数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '消费速率',
        position: 'right'
      }
    ],
    series: [
      {
        name: '消息数量',
        type: 'line',
        data: []
      },
      {
        name: '消费速率',
        type: 'line',
        yAxisIndex: 1,
        data: []
      },
      {
        name: '积压数量',
        type: 'line',
        data: []
      }
    ]
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 加载仪表盘数据
const loadDashboardData = async () => {
  try {
    // 加载系统统计数据
    const [systemRes, queueRes, monitorRes] = await Promise.all([
      getSystemList(),
      getQueueList(),
      getMonitorList()
    ])
    
    // 更新统计数据
    Object.assign(statistics, {
      totalSystems: systemRes.data.total,
      normalSystems: systemRes.data.normal,
      errorSystems: systemRes.data.error,
      testingSystems: systemRes.data.testing,
      totalQueues: queueRes.data.total,
      activeQueues: queueRes.data.active,
      backlogMessages: queueRes.data.backlog,
      avgConsumeDelay: queueRes.data.avgDelay,
      totalMonitors: monitorRes.data.total,
      todayAlerts: monitorRes.data.todayAlerts,
      pendingAlerts: monitorRes.data.pending,
      avgResponseTime: monitorRes.data.avgResponseTime,
      healthScore: monitorRes.data.healthScore,
      systemAvailability: monitorRes.data.availability,
      avgSystemResponseTime: monitorRes.data.avgResponseTime
    })
    
    // 更新图表数据
    updateCharts(systemRes.data.trend, queueRes.data.monitor)
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    ElMessage.error('加载仪表盘数据失败')
  }
}

// 更新图表数据
const updateCharts = (systemTrend, queueMonitor) => {
  // 更新系统调用趋势图表
  systemTrendChart.setOption({
    xAxis: {
      data: systemTrend.times
    },
    series: [
      {
        data: systemTrend.counts
      },
      {
        data: systemTrend.successRates
      },
      {
        data: systemTrend.responseTimes
      }
    ]
  })
  
  // 更新消息队列监控图表
  queueMonitorChart.setOption({
    xAxis: {
      data: queueMonitor.times
    },
    series: [
      {
        data: queueMonitor.messageCounts
      },
      {
        data: queueMonitor.consumeRates
      },
      {
        data: queueMonitor.backlogCounts
      }
    ]
  })
}

// 加载告警列表
const loadAlertList = async () => {
  alertLoading.value = true
  try {
    const res = await getMonitorHistory({
      page: alertPage.value,
      pageSize: alertPageSize.value
    })
    alertList.value = res.data.list
    alertTotal.value = res.data.total
  } catch (error) {
    console.error('加载告警列表失败:', error)
    ElMessage.error('加载告警列表失败')
  } finally {
    alertLoading.value = false
  }
}

// 处理告警
const handleProcessAlert = (row) => {
  currentAlert.value = row
  processForm.processType = ''
  processForm.remark = ''
  processAlertVisible.value = true
}

// 提交处理告警
const submitProcessAlert = async () => {
  if (!processFormRef.value) return
  
  try {
    await processFormRef.value.validate()
    processing.value = true
    
    await processAlert({
      id: currentAlert.value.id,
      ...processForm
    })
    
    ElMessage.success('处理成功')
    processAlertVisible.value = false
    loadAlertList()
  } catch (error) {
    console.error('处理告警失败:', error)
    ElMessage.error(error.message || '处理告警失败')
  } finally {
    processing.value = false
  }
}

// 导出告警
const handleExportAlerts = async () => {
  try {
    const res = await exportAlerts({
      page: alertPage.value,
      pageSize: alertPageSize.value
    })
    
    // 下载文件
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `告警列表_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出告警失败:', error)
    ElMessage.error('导出告警失败')
  }
}

// 工具方法
const getHealthTagType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 70) return 'warning'
  return 'danger'
}

const getHealthStatus = (score) => {
  if (score >= 90) return 'success'
  if (score >= 70) return 'warning'
  return 'exception'
}

const getAlertTypeTag = (type) => {
  const tagMap = {
    system: 'danger',
    business: 'warning',
    security: 'error',
    performance: 'info'
  }
  return tagMap[type] || ''
}

const getAlertTypeLabel = (type) => {
  const labelMap = {
    system: '系统告警',
    business: '业务告警',
    security: '安全告警',
    performance: '性能告警'
  }
  return labelMap[type] || type
}

const getAlertLevelTag = (level) => {
  const tagMap = {
    critical: 'danger',
    major: 'error',
    minor: 'warning',
    info: 'info'
  }
  return tagMap[level] || ''
}

const getAlertLevelLabel = (level) => {
  const labelMap = {
    critical: '严重',
    major: '重要',
    minor: '次要',
    info: '提示'
  }
  return labelMap[level] || level
}

const getAlertStatusTag = (status) => {
  const tagMap = {
    pending: 'warning',
    processing: 'info',
    resolved: 'success',
    ignored: 'info'
  }
  return tagMap[status] || ''
}

const getAlertStatusLabel = (status) => {
  const labelMap = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决',
    ignored: '已忽略'
  }
  return labelMap[status] || status
}

// 事件处理
const handleResize = () => {
  systemTrendChart?.resize()
  queueMonitorChart?.resize()
}

const handleAlertPageSizeChange = (val) => {
  alertPageSize.value = val
  loadAlertList()
}

const handleAlertPageChange = (val) => {
  alertPage.value = val
  loadAlertList()
}

const handleRefreshAlerts = () => {
  loadAlertList()
}

const handleViewAlertDetail = (row) => {
  currentAlert.value = row
  alertDetailVisible.value = true
}
</script>

<style lang="scss" scoped>
.integration-dashboard {
  padding: 20px;
  
  .dashboard-cards {
    margin-bottom: 20px;
    
    .dashboard-card {
      height: 100%;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .card-content {
        padding: 10px 0;
        
        .status-list,
        .queue-metrics,
        .alert-metrics,
        .health-metrics {
          .status-item,
          .metric-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .label {
              color: #909399;
            }
            
            .value {
              font-weight: bold;
              
              &.success {
                color: #67c23a;
              }
              
              &.warning {
                color: #e6a23c;
              }
              
              &.danger {
                color: #f56c6c;
              }
            }
          }
        }
        
        .health-metrics {
          .el-progress {
            margin-bottom: 15px;
          }
        }
      }
    }
  }
  
  .dashboard-charts {
    margin-bottom: 20px;
    
    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .alert-list-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-operations {
        .el-button {
          margin-left: 10px;
        }
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 